<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
 	https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html#一、发货信息录入接口
*/
namespace jy_wxappfaapi;
defined('BY_JYA') or exit('error');
class wxapp_api extends \plugin{
	protected $wxapp = null;
	public function __construct($wxapp_id=0){
		$wxapp_id=intval($wxapp_id);
		if(!$wxapp_id){
			$wxapp_id=$_SESSION['wxapp_id'];
		}
		$this->uniacid=$_SESSION['uniacid'];
		$params=array('uniacid'=>$this->uniacid);
		if($wxapp_id){
			$params['id']=$wxapp_id;
			$this->wxapp=pdo_get('core_account_wxapp',$params);
		}
		if(empty($this->wxapp)){
			unset($params['id']);
			$params['plugin_name']='jy_weishop';
			$this->wxapp=pdo_get('core_account_wxapp',$params);
		}
		if(empty($this->wxapp)){
			exi($wxapp_id.'ID商城小程序不存在！','error');
		}
		if (empty($this->wxapp['appid'])){
			exi('未填写小程序appid','error');
		}
		//APPsecret为必填项
		if(!$this->wxapp['appsecret']){
			exi('未填写小程序appsecret','error');
		}
		$_SESSION['wxapp_id']=$this->wxapp['id'];
		if($this->wxapp['expire']<TIMESTAMP || !$this->wxapp['access_token']){
			$this->getAccessToken('',true);
		}
	}
	public function getAccessToken($continue=false,$noexi=0){//获取access_token
		global $_AR;
		$noexi=$noexi?:$_SESSION['noexi'];
		if($this->wxapp['expire']>TIMESTAMP && !$continue && $this->wxapp['access_token']){
			return $this->wxapp['access_token'];
		}
		if(!$this->wxapp['appsecret']){
			return false;
		}else{
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->wxapp['appid']}&secret={$this->wxapp['appsecret']}";
		}
		$content = cfc('http')->ihttp_request($url);
		if(is_error($content) && !$noexi){
			exi('获取微信小程序授权失败, 请稍后重试！错误详情：'.$content['message'],'error');
		}
		$token = @json_decode($content['content'], true);
		if(empty($token) || empty($token['access_token']) && !$noexi) {
			exi('获取微信小程序授权失败, 请稍后重试！错误代码-' . $token['errcode'] . '，错误信息-' . $token['errmsg'].'错误详情：'.$this->error_code($token['errcode']),'error');
		}
		$record = array();
		$record['access_token'] = $token['access_token'];
		$record['expire'] = TIMESTAMP + $token['expires_in'] - 200;
		pdo_update('core_account_wxapp',$record,array('id'=>$this->wxapp['id']));
		$this->wxapp['access_token']=$token['access_token'];
		return $token['access_token'];
	}
	//发起http请求
	public function request($url,$post=null,$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$rurl=str_replace(array('{access_token}','ACCESS_TOKEN'),$this->wxapp['access_token'],$url);
		if($isjson){
			$headers = array('Content-Type' => 'application/json');
			$result=cfc('http')->ihttp_json($rurl,$post);
		}elseif($isrequest){
			$result=cfc('http')->ihttp_request($rurl,$post);
		}elseif($post){
			$result=cfc('http')->ihttp_post($rurl,$post);
		}else{
			$result=cfc('http')->ihttp_get($rurl);
		}
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if(($data['errcode']=='40001' || $data['errcode']=='42001') && $continue){
			$this->getAccessToken(true,1);
			$data=$this->request($url,$post,false,$direct,$return_error);
			return $data;
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='访问微信接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	//给第三方插件提供的额外接口，用于获取access_token
	public function access_token(){
		return $this->getAccessToken();
	}
	//发货信息录入接口
	public function fahuo($order=array()) {
		$url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token={access_token}";
		$post=array();
		$transaction_id=pdo_getcolumn('core_paylog',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['pay_id']),'transaction_id');
		$post['order_key']=array('order_number_type'=>2,'transaction_id'=>$transaction_id);
		if($order['sendtype']==1){
			if($order['peisong_id']){
				$logistics_type=2;
			}else{
				$logistics_type=1;
			}
		}elseif($order['sendtype']==2){
			$logistics_type=4;
		}else{
			$logistics_type=3;
		}
		$post['logistics_type']=$logistics_type;
		$post['delivery_mode']=1;
		$goodsid=pdo_getcolumn('jy_weishop_order_goods',array('uniacid'=>$_SESSION['uniacid'],'orderid'=>$order['id']),'goodsid');
		$item_desc=pdo_getcolumn('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$goodsid),'title');
		$shipping_list[]=array(
			'tracking_no'=>$order['expresssn']?:'',
			'express_company'=>$order['express']?:'',
			'item_desc'=>$item_desc,
		);
		$post['shipping_list']=$shipping_list;
		$post['upload_time']=date(DATE_RFC3339,time());
		$openid=pdo_getcolumn('core_fans',array('wxgid'=>$order['wxapp_id'],'mid'=>$order['mid'],'type'=>1,'uniacid'=>$_SESSION['uniacid']),'openid');
		if(!$openid){
			$app_uid=pdo_getcolumn('core_members',array('mid'=>$order['mid'],'uniacid'=>$_SESSION['uniacid']),'app_uid');
			if($app_uid){
				$openid=pdo_getcolumn('core_fans',array('wxgid'=>$order['wxapp_id'],'mid'=>$app_uid,'type'=>1,'uniacid'=>$_SESSION['uniacid']),'openid');
			}
			if(!$openid){
				$openid=pdo_getcolumn('core_fans',array('mid'=>$app_uid,'type'=>1,'uniacid'=>$_SESSION['uniacid']),'openid');
			}
			if(!$openid){
				return false;
			}
		}
		$post['payer']=array('openid'=>$openid);
		$post=ijson_encode($post);
		//file_put_contents(ROOT_D.'/1.txt',$post);
		$res=$this->request($url,$post,'','',true);
		
		$order['api_data']=$order['api_data']?:pdo_getcolumn('jy_weishop_order',array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),'api_data');
		if(!is_array($order['api_data'])){
			$order['api_data']=json_decode($order['api_data'],true);
		}
		if($res['errcode']){
			$order['api_data']['wxapp_fainfo']='小程序发货失败：'.$res['errcode'].','.$res['errmsg'];
		}else{
			$order['api_data']['wxapp_fainfo']='小程序发货成功';
		}
		pdo_update('jy_weishop_order',array('api_data'=>ijson_encode($order['api_data'])),array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['id']));
		if($res['errcode']){
			return false;
			exi('发货信息录入失败：'.$res['errcode'].','.$res['errmsg'],'error');
		}
		return '';
	}
}